<script setup lang="ts">
import { reactive, ref, unref, watch } from "vue";
import { Form } from "@/components/Form";
import { ElButton, ElCheckbox, ElMessage } from "element-plus";
import { required } from "@/utils/formRules";
import { useForm } from "@/hooks/web/useForm";
import api from "@/api";
import type { UserLoginType } from "@/api/types/loginType";
import { useCache } from "@/hooks/web/useCache";
import { useAppStore } from "@/store/modules/app";
import { usePermissionStore } from "@/store/modules/permission";
import { useRouter } from "vue-router";
import type { RouteLocationNormalizedLoaded, RouteRecordRaw } from "vue-router";
import getRouterList from "./roleMenu";
const appStore = useAppStore();
const permissionStore = usePermissionStore();

const { currentRoute, addRoute, push } = useRouter();

const { login } = api;

const rules = {
  username: [required],
  password: [required],
};

const schema = reactive<FormSchema[]>([
  {
    field: "title",
    colProps: {
      span: 24,
    },
  },
  {
    field: "userName",
    label: "用户名",
    component: "Input",
    colProps: {
      span: 24,
    },
    componentProps: {
      placeholder: "请输入用户名",
    },
  },
  {
    field: "password",
    label: "密码",
    component: "InputPassword",
    colProps: {
      span: 24,
    },
    componentProps: {
      style: {
        width: "100%",
      },
      placeholder: "请输入密码",
      onkeyup:(v)=>{
        v.cancelBubble = true
        if(v.keyCode == 13){
        signIn()
      }},
    },
  },
  {
    field: "tool",
    colProps: {
      span: 24,
    },
  },
  {
    field: "login",
    colProps: {
      span: 24,
    },
  },
]);
const remember = ref(false);

const { register, elFormRef, methods } = useForm();

const loading = ref(false);

const redirect = ref<string>("");

watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string;
  },
  {
    immediate: true,
  }
);

// 登录
const signIn = async () => {
  const formRef = unref(elFormRef);
  const { wsCache } = useCache();
  window.$clearws = ()=>{
    wsCache.set(appStore.getUserToken, null);
    wsCache.set(appStore.getUserInfo, null)
  }
  await formRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true;
      const { getFormData } = methods;
      const formData = await getFormData<UserLoginType>();
      const res = await login(formData)
        .catch(() => {})
        .finally(() => (loading.value = false));      
      if (res) {
        if(!res.data.roles.includes("admin")){
          ElMessage.error("您没有权限登录管理平台")
          return;
        }        
        window.$wsCache =wsCache
        wsCache.set(appStore.getUserInfo, res.data); 
        wsCache.set(appStore.getUserToken, res.data.jwt.access_token);                       
        // @ts-ignore
        if(window.__POWERED_BY_WUJIE__&&window.$wujie.props.doLogin) {
          // @ts-ignore
          window.$wujie.bus.$emit("doLogin", {recirect: redirect.value})
          return;
        }        
        await getRole();
        //await permissionStore.getRouterResources()
        push({ path:'/page/home' })
      }
    }
  });
};
// 获取角色信息
const getRole = async () => {
  //const appStore=useAppStore();
  const { wsCache } = useCache();
  //const userInfo = wsCache.get(appStore.getUserInfo);
            let routers:any=[...getRouterList()];

  wsCache.set("roleRouters", routers);
  await permissionStore.generateRoutes('backend',routers as any).catch(() => {});    
  permissionStore.getAddRouters.forEach((route) => {    
    addRoute(route as RouteRecordRaw); //动态添加可访问路由表      
  });            
  permissionStore.setIsAddRouters(true);    
  push({ path: redirect.value || permissionStore.addRouters[0].path });    
};
</script>

<template>
  <Form
    :schema="schema"
    :rules="rules"
    label-position="top"
    hide-required-asterisk
    size="large"
    @register="register"
    style="background:#fff; border-radius: 8px; box-shadow: 3px 3px 6px #999;"
  >
    <template #title>
      <h2 class="text-2xl font-bold text-center w-[100%]">登录</h2>
    </template>

    <template #tool>
      <div class="flex justify-between items-center w-[100%]">
        <ElCheckbox v-model="remember" label="记住我" size="small" />
        <!-- <ElLink type="primary" :underline="false">忘记密码</ElLink> -->
      </div>
    </template>

    <template #login>
      <ElButton :loading="loading" type="primary" class="w-[100%]" @click="signIn">
        登录
      </ElButton>
    </template>
  </Form>
</template>

<style lang="less" scoped>
:deep(.anticon) {
  &:hover {
    color: var(--el-color-primary) !important;
  }
}
</style>
